<template>
  <div class="assessment">
    <Nav
      backTitle="学前评估"
    />
    <SelectStudent
      :dataList="studentList"
      :currentSelect="currentStudent"
      @changeSelect="changeStudent"
      class="selectContent"
    ></SelectStudent>
    <ul
      class="a-list"
      v-if="testList.length"
    >
      <li
        class="a-item"
        v-for="(item,i) in testList"
        v-if="item.onlineTest"
      >
        <div class="subject-test">
          <p>
            <span class="line-title-test">校区 ：</span>
            <span class="school-area">{{item.onlineTest.campusName}}</span>
            <router-link
              v-if="item.onlineTest.isPass === '0'&&(item.hasExamLength<item.availableExamLength)"
              tag="em"
              :to="{path:'/test-enter',query:{onlineTestId:item.onlineTest.onlineTestId,gradeName:item.onlineTest.gradeName,subjectName:item.onlineTest.subjectName}}"
              class="to-test"
            >{{ item.hasExamLength?'重新诊断':'前往诊断'}}
            </router-link>
            <router-link
              v-if="item.onlineTest.isPass === '0'&&item.results&&item.hasExamLength==item.results.length&&item.availableExamLength&&item.results[item.results.length-1].status=='0'"
              tag="em"
              :to="{path:'/test-enter',query:{onlineTestId:item.onlineTest.onlineTestId,gradeName:item.onlineTest.gradeName,subjectName:item.onlineTest.subjectName}}"
              class="to-test"
            >重新诊断
            </router-link>

            <button
              class="btn copy"
              data-clipboard-target="#foo"
              v-if="item.onlineTest.isPass === '0'&&(item.hasExamLength<item.availableExamLength)"
            >
              <img
                src="../assets/img/copy-share.png"
                alt=""
              >
            </button>
            <button
              class="btn copy"
              data-clipboard-target="#foo"
              v-if="item.onlineTest.isPass === '0'&&item.hasExamLength==item.results&&item.availableExamLength&&item.results[item.results.length-1].status=='0'"
            >
              <img
                src="../assets/img/copy-share.png"
                alt=""
              >
            </button>
          </p>
          <p>
            <span class="line-title-test">年级 ：</span>
            <span>{{item.onlineTest.gradeName}}</span>
            <input
              id="foo"
              class="copy-input"
              :value='copyUrl+"test-enter?"+encodeUrl("onlineTestId="+item.onlineTest.onlineTestId+"&gradeName="+item.onlineTest.gradeName+"&subjectName="+item.onlineTest.subjectName)'
            >
          </p>
          <p>
            <span class="line-title-test">科目 ：</span>
            <span>{{item.onlineTest.subjectName}}</span>
            <span
              v-if="item.onlineTest.externalScoreType !== '0' && !item.onlineTest.externalScore && item.onlineTest.isPass === '0'"
              class="external-score"
              @click="handleExternalScore(item.onlineTest)"
            >输入成绩</span>
          </p>
        </div>
        <div
          class="external"
          v-if="item.onlineTest.externalScoreType !== '0' && item.onlineTest.externalScore"
        >
          <span v-if="item.onlineTest.externalScoreType === '1'">中考单科分数：</span>
          <span v-if="item.onlineTest.externalScoreType === '2'">学业诊断名次：</span>
          <em>{{item.onlineTest.externalScore | formatNumber(0)}}</em>{{item.onlineTest.externalScoreType === '1' ? '分': '名'}}
          <span class="test-time">{{item.onlineTest.externalScoreUpdateTime | formatDate('YYYY-MM-DD H:mm:ss')}}</span>
        </div>
        <ul
          v-if="item.results || (item.onlineTest.externalScoreType !== '0' && item.onlineTest.externalScore)"
          class="test-status"
        >
          <li v-for="(rItem,rI) in item.results">
            {{num[rI]}}考成绩 ：
            <em>{{rItem.score}}</em>分
            <span class="test-time">{{rItem.createTime | formatDate('YYYY-MM-DD H:mm:ss')}}</span>
          </li>
          <li v-if="item.onlineTest.isPass === '1'">
            <img src="../assets/img/tip-line.png" />
            <span class="assess">已通过</span>
          </li>
          <li v-else>
            <img src="../assets/img/tip-line.png" />
            <span class="assess">未通过</span>
          </li>
        </ul>
      </li>
    </ul>
    <empty v-else />
  </div>
</template>

<script>
import Clipboard from 'clipboard'
import Nav from 'components/nav/nav.vue'
import Empty from 'components/empty.vue'
import SelectStudent from 'components/select/select.vue'
import api from 'util/xhr'
import { mapState, mapActions } from 'vuex'
export default {
  name: 'assessment',
  components: {
    Nav,
    SelectStudent,
    Empty
  },
  computed: {
    ...mapState({
      studentList: state => {
        return state.studentList
      },
      currentStudent: state => {
        return state.currentStudent
      }
    })
  },
  data() {
    return {
      showStudents: false,
      showName: '',
      testList: [],
      num: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十'],
      copyUrl: document.location.host + '/',
      redirectUrl: ''
    }
  },
  created() {
    let { studentId } = this.$route.query
    this.loadStudent().then(() => {
      if (this.studentList.length === 0) {
        this.$alert({ content: '目前没有学员，请增加学员' })
      } else {
        if (studentId) {
          for (let item of this.studentList) {
            if (item.studentId === studentId) {
              this.changeCurrentStudent(item)
              break
            }
          }
        }
        this.getTestList(this.currentStudent.studentId)
      }
    })
  },
  mounted() {
    $(window).scrollTop(0)
    var clipboard = new Clipboard('.btn')
    clipboard.on('success', e => {
      e.clearSelection()
      this.$alert({
        content: '学前评估链接已复制到剪切板，请将该链接发送给他人'
      })
    })

    clipboard.on('error', function(e) {
      console.error('Action:', e.action)
      console.error('Trigger:', e.trigger)
    })
  },
  methods: {
    ...mapActions({
      loadStudent: 'loadStudent',
      changeCurrentStudent: 'changeCurrentStudent'
    }),
    handleExternalScore(onlineTest) {
      let studentName = this.currentStudent.studentName
      this.$router.push({
        path: '/external-score',
        query: {
          name: studentName,
          onlineTestId: onlineTest.onlineTestId,
          externalScoreType: onlineTest.externalScoreType
        }
      })
    },
    changeStudent(studentObj) {
      this.getTestList(studentObj.studentId)
    },
    getTestList(studentId) {
      api
        .post('/api/m/onlineTestList', {
          studentId: studentId
        })
        .then(
          data => {
            data.map((item, i) => {
              item.availableExamLength =
                (item.onlineTest &&
                  item.onlineTest.availableExamPaperIds &&
                  item.onlineTest.availableExamPaperIds.split(',').length) ||
                0
              item.hasExamLength = (item.results && item.results.length) || 0
              item.classType = ''
              let bigScore = 0
              let lastExamId = ''
              item.results &&
                item.results.map(rItem => {
                  if (Number(rItem.score) >= bigScore) {
                    bigScore = Number(rItem.score)
                    lastExamId = rItem.onlineTestResultId
                  }
                })
            })

            this.testList = data
          },
          desc => {
            this.$alert({ content: desc })
          }
        )
    },
    getResult(id, index) {
      api
        .post('/api/m/onlineTestResult', {
          onlineTestResultId: id
        })
        .then(
          data => {
            if (data.levels && data.levels.length) {
              data.levels = Array.from(new Set(data.levels))
              let classType = [
                { id: '1', value: '不区分' },
                { id: '2', value: '核心素养班' },
                { id: '3', value: '新课标S班' },
                { id: '4', value: '新课标A班' },
                { id: '5', value: '新课标B班' },
                { id: '6', value: '启航班' },
                { id: '7', value: '研习班' }
              ]
              let cType = []
              data.levels.map(item => {
                classType.map(cItem => {
                  if (cItem.id === item) {
                    cType.push(cItem.value)
                  }
                })
              })
              this.testList[index].classType = cType.join(',')
            }
          },
          desc => {
            this.$alert({ content: desc })
          }
        )
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
.selectContent {
  position: fixed;
  left: 0;
  top: 110px;
  z-index: 9;
}
.assessment {
  background: #f8f8f8;
  height: 100%;
  padding-top: 216px;
}
.a-list {
  font-size: 28px;
  color: #333;
}

.a-list .a-item {
  margin-bottom: 20px;
  background: white;
  padding: 20px 46px;
}

.a-list .a-item p {
  display: flex;
  align-items: center;
  height: 60px;
  position: relative;
}

.line-title-test {
  font-weight: bold;
}

.to-test {
  position: absolute;
  right: 0;
  color: #3271f1;
  display: inline-block;
  padding: 4px 10px;
  border: 2px solid #3271f1;
  border-radius: 12px;
}

.test-status li,
.external {
  height: 90px;
  display: flex;
  align-items: center;
  position: relative;
  border-top: 1px dashed #ddd;
}

.test-status em,
.external em {
  color: #ff0000;
  font-size: 36px;
  font-style: italic;
  margin-right: 10px;
  font-weight: bold;
}

.test-status .test-time,
.external .test-time {
  position: absolute;
  right: 0;
  top: 30px;
  font-size: 24px;
  color: #999;
}

.test-status li:last-child {
  height: 70px;
  display: block;
  line-height: 90px;
}

.test-status .assess {
  color: #ff9600;
}

.test-status img {
  position: relative;
  top: 4px;
  margin-right: 10px;
  width: 32px;
}

.copy {
  font-size: 28px;
  position: absolute;
  right: 170px;
  background: transparent;
  border: 0;
  /*top: 1rem;*/
  height: 100%;
  width: 50px;
}
.copy img {
  width: 32px;
  height: auto;
}
.copy-input {
  opacity: 0;
  height: 1px;
}
.external-score {
  position: absolute;
  right: 0;
  color: #00a7eb;
  text-decoration: underline;
}
.school-area {
  display: inline-block;
  max-width: 230px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
